package org.yzh.scheduler.component.auth;

import org.springframework.web.filter.OncePerRequestFilter;
import org.yzh.commons.util.JWTUtils;
import org.yzh.scheduler.model.entity.UserDO;
import org.yzh.scheduler.model.enums.Role;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthenticationFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authentication");
        if (token == null)
            token = request.getParameter("token");

        if (token == null) {
            response.setStatus(403);
            response.getWriter().println("用户认证失败");
            return;
        }

        UserDO user = JWTUtils.unsign(token, UserDO.class);
        if (user != null) {
            if (user.getRole() == Role.User) {
                response.setStatus(403);
                response.getWriter().println("没有权限访问");
                return;
            }
            request.setAttribute("user", user);
            filterChain.doFilter(request, response);
        }
    }
}